// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <map>
#include <memory>
#include <string>
#include <vector>

#include <rapidjson/document.h>

// internal
#include "coin2/exchange/base/feed/processor.h"
#include "coin2/exchange/base/market/enums.h"
#include "coin2/exchange/di/constant.h"

namespace coin2::exchange::phemex_base::feed_v1 {
namespace impl {
using coin2::exchange::base::executor::TopicRecordPacket;
using namespace coin2::exchange::base::symbology;
class PhemexBaseFeedProcessor : public base::feed::FeedParsingProcessor {
 public:
  explicit PhemexBaseFeedProcessor(
      const std::string& system_name,
      const coin2::exchange::di::ConstantInjection& ci,
      const feed::RawParserConfig& config,
      const MarketExchangeApi& mea)
      : FeedParsingProcessor(
            system_name,
            mea,
            ci,
            config) {
    if (mea.String() == "Futures.Phemex.v1") {
      price_multiplier_ = 1e-4;
      qty_multiplier_ = 1;
    }else if (mea.String() == "Futures.Phemex.v1-linear") {
      price_multiplier_ = 1;
      qty_multiplier_ = 1;
    } else {
      price_multiplier_ = 1e-8;
      qty_multiplier_ = 1e-8;
    }
  }
  void OnTopicRecord(const base::executor::TopicRecordPacket& packet) override;

  std::string ExtractChannel(const rapidjson::Document& doc) {
    if (doc.HasMember("book") || doc.HasMember("orderbook_p")) {
      return "orderbook";
    } else if (doc.HasMember("trades") || doc.HasMember("trades_p")) {
      return "trade";
    } else if (doc.HasMember("market24h")) {
      return "market24h";
    } else if (doc.HasMember("method") &&
               StringStartsWith(doc["method"].GetString(), "perp_market24h_pack_p")) {
      return "perp_market24h_pack_p";
    } else if (doc.HasMember("url")) {
      const std::string url = doc["url"].GetString();
      if (url.find("public/md/v2/kline") != std::string::npos) {
        return "kline_rest";
      } else {
        return "unknown";
      }
    } else {
      return "unknown";
    }
  }

 private:
  double GetPriceMultiplier(std::string_view native_symbol);
  double price_multiplier_;
  double qty_multiplier_;
};
}  // namespace impl
using impl::PhemexBaseFeedProcessor;
}  // namespace coin2::exchange::phemex_base::feed_v1
